package com.anclick.mywatch;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;

/**
 * AppWidget Configuration Activity
 * 
 * com.anclick.mywatch
 * DateWidgetConfigureActivity.java
 *
 * @author junhwan_kim
 * @date 2011. 4. 29. 오전 10:59:49
 * @Version 
 */
public class MyWatchConfigure extends Activity {
	
	private static final String TAG = "MyWatch";
	
	final Context context = MyWatchConfigure.this;
	
	/// On/Off할 Item의 Static Variable
	private static int SHOW_AMPM = 0;
	private static int SHOW_DATE = 1;
	private static int SHOW_BACKGROUND = 2;
	
	/// Path 관련  Static Variable
	public static String SUB_PATH = "/mywatch/theme";
	
	/// Widget Id
	private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	
	/// Spinner에 Directory를 list하기 위한 변수 
	private ArrayList<String> arrayDirectory;
	private Spinner spinner;
	private ArrayAdapter<String> adapter;
	private String selectedDirectory;
	
	/// ListView에 on/off할 item을 list하기 위한 변수
	private ArrayList<String> mItems;
	private ArrayAdapter<String> mAdapter;
	private ListView mList;
	
	/// On/Off Toggle Variable
	private static String[] settingToggle;
	private static int SHOW_TOTAL = 3;
	
	/**
	 * 
	 * @Constructor DateWidgetConfigureActivity
	 *
	 * @author jun2yah
	 * @date 2011. 5. 5. 오후 6:39:37
	 */
	public MyWatchConfigure() {
        super();
    }
	
	/**
	 * Widget Id 추출 
	 * Image Directory를 Spinner에 List
	 * Setting On/Off Item을 ListView에 List
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 * @Method onCreate
	 * @param savedInstanceState
	 *
	 * @author junhwan_kim
	 * @date 2011. 4. 29. 오전 10:59:32
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

	    Log.i(TAG, "DateWidgetConfigureActivity-onCreate()");
		
	    /// 기본 선택값을 CANCELED로 지정해 사용자가 뒤로가기로 Activity를 닫는 경우 취소 결과값을 반환하도록 함.
	    setResult(RESULT_CANCELED);
	    
	    setContentView(R.layout.appwidget_configure);
	    
	    settingToggle = new String[SHOW_TOTAL];
	    
//	    Intent intent = getIntent();
//	    Bundle extras = intent.getExtras();
//	    if (extras != null) {
//	    	mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
//	    }
//	    if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
//	    	finish();
//	    }
	    
	    /// 추가하려는 widgetID 추출
	    Intent intent = getIntent();
	    mAppWidgetId = intent.getIntExtra("SELECTED_WIDGET_ID", AppWidgetManager.INVALID_APPWIDGET_ID);
	    
	    /// 정상적인 경로로 호출되지 않은 경우 Activity를 종료한다.
	    if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
	    	mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
	    	if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
	    		finish();
	    	} else {
	    		String [] initPrefValue = {String.valueOf(mAppWidgetId), "Default Image", "0", "0", "0"};
		    	MyWatchPreferences.setPref(context, initPrefValue);
		    	settingToggle[SHOW_AMPM] = "0";
		    	settingToggle[SHOW_DATE] = "0";
		    	settingToggle[SHOW_BACKGROUND] = "0";
	    	}
	    }
	    
	    /// Shared Preferences에서 설정값을 가져온다., junhwan_kim, 2011.05.12
	    String[] prefValue = MyWatchPreferences.getPref(this, mAppWidgetId);
	    selectedDirectory = prefValue[MyWatchPreferences.IMAGEPATH];
    	settingToggle[SHOW_AMPM] = prefValue[MyWatchPreferences.AMPM];
    	settingToggle[SHOW_DATE] = prefValue[MyWatchPreferences.DATE];
    	settingToggle[SHOW_BACKGROUND] = prefValue[MyWatchPreferences.BACKGROUND];
	    
	    /// Image Path
	    File sdPath = Environment.getExternalStorageDirectory();
	    File rootPath = new File(sdPath.getAbsolutePath() + SUB_PATH);
	    
	    /// Spinner에 들어갈 Directory명을 ArrayList에 추가한다.
	    int position = 0;
	    arrayDirectory = new ArrayList<String>();
	    
	    /// 패키지에 포함된 디폴트 이미지 (디렉토리에 이미지가 없는 경우에 사용)
	    arrayDirectory.add("My Watch");		
	    
	    /// Image를 불러올 root path 존재 확인 후 없으면 생성
	    if (rootPath.exists()) {
	    	String[] list = rootPath.list();
	    	
	    	/// Root Path에 Directory or File이 있는지 확인.
	    	if (list != null) {
	    		int i = 0;
		    	for(String dir : list) {
		    		File f = new File(rootPath.toString() + "/" + list[i]);
		    		
		    		/// list에 Directory가 있으면~
		    		if (f.isDirectory()) {
			    		arrayDirectory.add(dir);
		    		}
		    		
		    		/// 선택한 디렉토리의 position
		    		if (dir.equals(selectedDirectory)) { 
		    			position = i + 1;
		    		}
		    		i++;
		    	}
	    	}
	    } else {
	    	rootPath.mkdirs();	/// root directory 생성 
	    }
	    
	    /// 스피너에 디렉토리 이름을 항목으로 입력한다.
	    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayDirectory);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner = (Spinner)findViewById(R.id.spinner01);
	    spinner.setAdapter(adapter);
		spinner.setSelection(position);
	    
		/// 스피너 선택 리스너에서 선택된 디렉토리명을 저장.
	    spinner.setOnItemSelectedListener(mItemSelectedListener);
	    
	    /// ListView에 날짜, 요일을 AppWidget에 on/off 여부를 선택하게 한다.
	    mItems = new ArrayList<String>();
	    mItems.add("AM/PM");
	    mItems.add("Date");
	    mItems.add("Background");
	    
	    mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, mItems);
	    mList = (ListView)findViewById(R.id.listView01);
	    mList.setAdapter(mAdapter);
	    mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	    mList.setOnItemClickListener(mItemClickListener);
	    
	    /// get seetingToggle & Item Check
	    /// !! preferences에서 값 가져오는 루틴 필요.
	    mList.setItemChecked(SHOW_AMPM, prefValue[MyWatchPreferences.AMPM].equals("1") ? true : false);
	    mList.setItemChecked(SHOW_DATE, prefValue[MyWatchPreferences.DATE].equals("1") ? true : false);
	    mList.setItemChecked(SHOW_BACKGROUND, prefValue[MyWatchPreferences.BACKGROUND].equals("1") ? true : false);
	    
	    /// 버튼 클릭 시 해당 디렉토리의 이미지로 시계 추가
	    findViewById(R.id.btn01).setOnClickListener(mClickListener);
	}
	
	/**
	 * Interface definition for a callback to be invoked when an item in this view has been selected.
	 * Spinnner 선택 이벤트
	 * 
	 * @see android.widget.AdapterView.OnItemSelectedListener
	 * 
	 * @author junhwan_kim
	 * @date 2011. 4. 29. 오전 11:10:49
	 */
	AdapterView.OnItemSelectedListener mItemSelectedListener = new AdapterView.OnItemSelectedListener() {
		/**
		 * Callback method to be invoked when an item in this view has been selected.
		 */
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			/// 선택한 디렉토리
			selectedDirectory = arrayDirectory.get(position);
//			Toast.makeText(getBaseContext(), selectedDirectory + " selected.", Toast.LENGTH_SHORT).show();
		}
		
		/**
		 * Callback method to be invoked when the selection disappears from this view.
		 */
		public void onNothingSelected(AdapterView<?> parent) {
			
		}
	};

	/**
	 * Interface definition for a callback to be invoked when an item in this AdapterView has been clicked.
	 * ListView Click 이벤트
	 * 
	 * @see android.widget.AdapterView.OnItemClickListener
	 * 
	 * @author junhwan_kim
	 * @date 2011. 4. 29. 오전 11:29:21
	 */
	AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
		/**
		 * Callback method to be invoked when an item in this AdapterView has been clicked.
		 */
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			/// setting 값을 toggle한다.
			/// !! Preferences에서 값 가져오는 루틴 필요.
			if (settingToggle[position].equals("1")) {
				settingToggle[position] = "0";
			} else {
				settingToggle[position] = "1";
			}
		}
	};
	
	/**
	 * Interface definition for a callback to be invoked when a view is clicked.
	 * OK 버튼 Click 이벤트
	 * 
	 * @see android.view.View.OnClickListener
	 * 
	 * @author junhwan_kim
	 * @date 2011. 4. 29. 오전 11:29:51
	 */
	Button.OnClickListener mClickListener = new Button.OnClickListener() {
		/**
		 * Called when a view has been clicked.
		 */
		public void onClick(View v) {
			if(selectedDirectory != null) {
		    	/// widgetID별로 설정을 SharedPreference에 저장한다.
				String [] prefValue = {String.valueOf(mAppWidgetId), 
						selectedDirectory,
						settingToggle[SHOW_AMPM],
						settingToggle[SHOW_DATE],
						settingToggle[SHOW_BACKGROUND]};
				 
		    	MyWatchPreferences.setPref(context, prefValue);
		    	MyWatchPreferences.setWidgetId(context, String.valueOf(mAppWidgetId));
		    	
		    	/// 최초의 업데이트를 수행한다.
		    	AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
		    	MyWatchProvider.updateWidget(context, appWidgetManager, mAppWidgetId);
		    	
		    	/// Configure의 일반 종료 처리
		    	Intent intent = new Intent();
		    	intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
		    	setResult(RESULT_OK, intent);
		    	finish();
		    }
		}
	};
}
